import React from 'react'
import {Form, Icon, Input, Button} from 'antd';
import style from './index.css'
import {myFetch} from '../../utils/func.js'

const FormItem = Form.Item;

class NormalLoginForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {}
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                let loginName = values.loginname;
                let password = values.password;
                myFetch('/api/v1/user/login.php', {
                    loginname: loginName,
                    password: password
                })
                    .then((data) => {
                        if (data !== false) {
                            let userInfo = data.data[0];
                            let avatarUrl = userInfo.avatarUrl;
                            let nickName = userInfo.nickname;
                            sessionStorage .setItem('nickname', nickName);
                            sessionStorage .setItem('avatarUrl', avatarUrl);
                            sessionStorage .setItem('isLogin', true);
                            this.props.sub(userInfo);
                        }

                    })

            }
        });
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        return (
            <Form onSubmit={this.handleSubmit} className={style.loginForm}>
                <p className={style.head}>阿Q联盟</p>
                <FormItem className={style.loginInput}>
                    {getFieldDecorator('loginname', {
                        rules: [{required: true, message: '请输入用户名!'}],
                    })(
                        <Input prefix={<Icon type="user" style={{fontSize: 13}}/>} placeholder="用户名"/>
                    )}
                </FormItem>
                <FormItem className={style.loginInput}>
                    {getFieldDecorator('password', {
                        rules: [{required: true, message: '请输入密码!'}],
                    })(
                        <Input prefix={<Icon type="lock" style={{fontSize: 13}}/>} type="password" placeholder="密码"/>
                    )}
                </FormItem>
                <FormItem>
                    <Button type="primary" htmlType="submit" className={style.loginButton}>
                        登录
                    </Button>
                </FormItem>
            </Form>
        );
    }
}

const WrappedNormalLoginForm = Form.create()(NormalLoginForm);
export default WrappedNormalLoginForm;
